<?php


declare(strict_types=1);

namespace App\Controller\Abell;

use App\Controller\AbstractController;
use App\Server\CurlApi;
use App\Utils\ApiUtils;
use App\Utils\Upload;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Extend\Wx\Wxlogin as WxloginExtend;
// mongodb
use Hyperf\Mongodb\MongoDb;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Parallel;//引入@Inject注解

/**
 * @Controller()
 */
class WxloginController extends AbstractController
{
    /**
     * @Inject()
     * @var MongoDb
     */
    protected $mongoDbClient;

    private $db_name = 'pc_wxuser';

    /**
     * 使用mangoDB登录
     * Abell 2020/5/21
     * @RequestMapping(path="/abell/wxlogin/index", methods="get")
     */
    public function index(RequestInterface $request){
        $has_user = $this->mongoDbClient->fetchAll($this->db_name,['openid' => $request->input('openid','ogtzs4LbS6R8Y_ec6k64nUNWIeC')]);
        var_dump(gettype($has_user));

        return $has_user;
    }


    /** GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
     * 登录凭证校验
     * @param string $code 通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程
     * @return array
     * Abell 2020/5/14
     * @RequestMapping(path="/abell/wxlogin/code2_session", methods="get")
     */
    public function code2_session(RequestInterface $request){
        $code = $request->input('code');
        $appid = config('web.wx_account.appid');
        $appscret = config('web.wx_account.appsecret');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appscret.'&js_code='.$code.'&grant_type=authorization_code';
        var_dump($url);
        $wechat_login = make(CurlApi::class)->get($url);
        var_dump($wechat_login);
        // 处理返回内容
        $wechat_login_data = json_decode($wechat_login['data'],true);
        var_dump($wechat_login_data);
        return  $wechat_login;
    }

    // getPaidUnionId
    /** GET https://api.weixin.qq.com/wxa/getpaidunionid?access_token=ACCESS_TOKEN&openid=OPENID
     * 用户支付完成后，获取该用户的 UnionId，无需用户授权。本接口支持第三方平台代理查询。
     * @param string $openid 必须  用户支付唯一标识符
     * @param string $transaction_id  微信支付订单号
     * @param string $mch_id  微信支付分配的商户号，和商户订单号配合使用
     * @param string $out_trade_no  微信支付商户订单号，和商户号配合使用
     * @return array
     * Abell 2020/5/14
     * @RequestMapping(path="/abell/wxlogin/get_paid_union_id", methods="get")
     */
    public function get_paid_union_id(RequestInterface $request){
        $data = make(WxloginExtend::class)->check_token_redis($request->input('force',false));
        $openid = $request->input('openid');
        $url = 'https://api.weixin.qq.com/wxa/getpaidunionid?access_token='.$data.'&openid='.$openid;
        $wechat_union_id = make(CurlApi::class)->get($url);
        return  $wechat_union_id;
    }

    /** 获取微信token数据
     * @param bool force 是否强制更新token,默认是false不强制更新
     * @return array
     * Abell 2020/5/8
     * @RequestMapping(path="/abell/wxlogin/get_token", methods="get")
     */
    public function getToken(RequestInterface $request){
        $data = make(WxloginExtend::class)->check_token_redis($request->input('force',false));
        return $data;
    }

    /**
     * 小程序登录注册接口
     * Abell
     * 2020/4/16 15:21
     * @RequestMapping(path="/abell/wxlogin/login", methods="get")
     */
    public function login(RequestInterface $request)
    {
        if ($request->has('openid')) {
            $has_user = WxuserModel::where(['openid' => $request->input('openid')])->value('id');
            if ($has_user) {
                //存在的老用户登录
                $user_info = $this->checkLogin($request->all(), $has_user);
                return $this->response->json(ApiUtils::send($user_info['code'], $user_info['msg'], $user_info['token'], 1));
            } else {
                // 不存在的新用户授权登录
                $user_info = $this->checkReg($request->all());
                return $this->response->json(ApiUtils::send($user_info['code'], $user_info['msg'], $user_info['token'], 1));
            }
        } else {
            return $this->response->json(ApiUtils::send(500, 'Error', '禁止访问', 1));
        }
    }

    /**
     * 小程序授权登录检查接口
     * Abell
     * 2020/4/18 15:21
     */
    public function checkLogin($request, $has_user)
    {
        // 老用户登录,更新登录时间
        $update_user = WxuserModel::where(['id' => $has_user])
            ->update(['update_time' => time()]);
        if ($update_user) {
            // 更新登录时间成功  获取token
            $token = JwtToken::authorizations($has_user, $request['openid'], '2');
            // 统计访问
            $visit = $this->visit($has_user);
            $token['visit'] = $visit;
            $return_data = ['code' => 0, 'msg' => '登录成功', 'token' => $token];
        } else {
            // 更新登录时间失败
            $return_data = ['code' => 403, 'msg' => '登录故障', 'token' => ''];
        }
        return $return_data;
    }

    /**
     * 小程序授权登录检查接口
     * Abell
     * 2020/4/18 15:21
     */
    public function checkReg($request)
    {
        //新用户授权登录 post 先写入数据,后期再获取更新用户信息
        $update_data = ['add_time' => time(), 'update_time' => time(), 'openid' => $request['openid']];
        if (array_key_exists('nickname', $request)) $update_data['nickname'] = $request['nickname'];
        if (array_key_exists('avatarurl', $request)) $update_data['avatarurl'] = $request['avatarurl'];
        if (array_key_exists('gender', $request)) $update_data['gender'] = $request['gender'];
        if (array_key_exists('country', $request)) $update_data['country'] = $request['country'];
        if (array_key_exists('province', $request)) $update_data['province'] = $request['province'];
        if (array_key_exists('city', $request)) $update_data['city'] = $request['city'];
        if (array_key_exists('language', $request)) $update_data['language'] = $request['language'];
        if (array_key_exists('mobile', $request)) $update_data['mobile'] = $request['mobile'];
        if (array_key_exists('haspay', $request)) $update_data['haspay'] = $request['haspay'];
        $new_user = WxuserModel::insertGetId($update_data);
        if ($new_user) {
            // 授权注册成功  获取token
            $token = JwtToken::authorizations($new_user, $request['openid'], '2');
            // 统计访问
            $visit = $this->visit($new_user);
            $token['visit'] = $visit;
            $return_data = ['code' => 0, 'msg' => '授权注册成功', 'token' => $token, 'visit' => $visit];
        } else {
            // 授权注册失败
            $return_data = ['code' => 402, 'msg' => '授权注册故障', 'token' => '', 1];
        }
        return $return_data;
    }

    /**
     * 访问页面数据统计  login2reg
     * Abell
     * 2020/4/20
     */
    private function visit($openid)
    {
        // 查询用户当天是否已经访问过了
        $today_zero = strtotime(date('Y-m-d', time()));
        $where = ['openid' => $openid, 'type_explain' => 'login2reg'];
        $has_visit = WxvisitModel::where($where)->where('add_time', '>', $today_zero)->value('id');
        if ($has_visit) {
            // 存在访问数据,直接返回
            return '更新用户访问时间';
        } else {
            // 新增访问记录
            $new_visit = WxvisitModel::insertGetId(['openid' => $openid, 'type_explain' => 'login2reg', 'add_time' => time(), 'update_time' => time()]);
            return '新增用户访问记录';
        }
    }
}